<template>
    <div class="container">
        <el-button type="primary" @click="initDicom">初始化</el-button>
        <el-button type="primary" @click="loadDicomViewer">加载图像</el-button>

        <div id="dicom-viewport" class="viewport"></div>
    </div>
</template>

<script setup>
import { useRoute } from 'vue-router';
import { DicomDataService } from '@/api/pacs/dicomService.js'
// import { DicomDataService } from '@/services/dicomService.js'
import { ref } from 'vue';
import {
  Enums as csEnums,
  RenderingEngine,
  imageLoader,
 
  init as coreInit
} from '@cornerstonejs/core'

import cornerstoneDICOMImageLoader from '@cornerstonejs/dicom-image-loader'
import { onMounted } from "vue";


const route = useRoute();
// 创建DicomDataService实例
const dicomService = new DicomDataService();


const studyId = ref() //studyID
const studyInstanceUid = ref('')  //studyUId
const seriesInstanceUid = ref('') //Series UID
const seriesInstanceUidOptions = ref([])
let imageIds=ref([])
// 视图DOM引用
const viewportRef = ref(null)

/***
 *  ViewPort 和 renderingEngine
 */

let viewportId = 'CT_STACK'
let renderingEngineId = 'myRenderingEngine'
let viewPort = null
let renderingEngine = null







/***
 * 显示Dicom图像
 */

async function loadDicomViewer(){
        const serId="1.2.840.113619.2.428.3.2831168388.99.1649501908.947";
        const studyId="1.2.840.113619.2.428.3.2831168388.99.1649501908.942";
        // 1. 从后端获取图像信息（stydy id 和序列id 查询）
        const seriesData = await dicomService.createImageIds(studyId,serId);
        console.log("序列数据V3",seriesData);
        
        const viewPort = renderingEngine.getViewport(viewportId);

        console.log('获取到序列数据:', seriesData)
        
        // 2. 注册自定义图像加载器（有用吗）
        registerQiniuImageLoader();
        
     
        // 3. 设置图像ID列表
        imageIds.value = seriesData.imageIds
        
        // 4. 加载和显示图像
        if (imageIds.value.length > 0) {
            console.log('设置图像堆栈:', imageIds.value)
            
            // 确保 viewPort 存在且有 setStack 方法
            console.log("ViewPort",viewPort);
            if (!viewPort || typeof viewPort.setStack !== 'function') {
                console.log("===不存在setStack==")
                throw new Error('ViewPort 未正确初始化或缺少 setStack 方法')
            } 
            console.log(typeof viewPort.setStack)
            console.log(viewPort.setStack)

            // 对于网络图像，直接使用 setStack
            await viewPort.setStack(imageIds.value)
            
       
            console.log('DICOM序列加载完成V3')
        } else {
            console.warn('没有找到图像数据')
            alert('没有找到图像数据，请检查 Study 和 Series UID')
        }
}


/**
 * 注册七牛云图像加载器
 */
function registerQiniuImageLoader() {
  imageLoader.registerImageLoader('qiniu', (imageId) => {
    const promise = (async () => {
            try {
                // 解析图像ID，把标志去掉
                const url = imageId.replace('qiniu:', '').split('?')[0]
                console.log("===url=========",url);

                // 从七牛云获取DICOM数据
                const arrayBuffer = await dicomService.fetchDicomDataFromQiniu(url);

                // const arrayBuffer = await dicomService.fetchDicomFromQiniu(url)
                console.log("输出Buffewr");
                console.log(arrayBuffer);
                console.log("==开始==")
                // 使用DICOM图像加载器处理数据
                const dicomImageLoader = cornerstoneDICOMImageLoader.wadouri.loadImage
                
                // 创建临时的wadouri格式imageId
                const blob = new Blob([arrayBuffer], { type: 'application/dicom' })
                const blobUrl = URL.createObjectURL(blob)
                const wadouriImageId = `wadouri:${blobUrl}`
                console.log("输出wadouri",wadouriImageId);
              
                // 调用原始的DICOM加载器
                const imageLoadObject = dicomImageLoader(wadouriImageId)
                console.log("imageLoadObject",imageLoadObject);
                // 等待图像加载完成
                const image = await imageLoadObject.promise
                console.log('图像加载成功:', image)
                
                // 清理临时URL
                URL.revokeObjectURL(blobUrl)
                
                return image
                
            } catch (error) {
                console.error('七牛云图像加载失败:', {
                    imageId,
                    error: error.message,
                    stack: error.stack
                })
                throw error
            }
        })()

    return {
      promise,
      cancelFn: () => {
        console.log('取消图像加载');
      }
    };
  });
}
/**
 * 初始化组件
 */
async function initDicom(){
    viewportRef.value=document.getElementById("dicom-viewport");
    console.log("====初始化开始V3====");

    await coreInit();
    await cornerstoneDICOMImageLoader.init();

    const tempRenderingEngine = new RenderingEngine(renderingEngineId);

    const viewportInput = {
      viewportId,
      element:viewportRef.value,
      type: csEnums.ViewportType.STACK,
    };

    
    tempRenderingEngine.enableElement(viewportInput);

    renderingEngine=tempRenderingEngine;
    console.log("====初始化完成====")


}


</script>
<style scoped>
  .viewport {
            width: 800px;
            height: 800px;
          
            margin-top: 20px;
            margin-left: 20px;
          
            background-color: black;
  }
</style>